package com.liuyu.common.framework.common.utils;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;

import java.util.concurrent.*;

/**
 * @ClassName GlobalEceutorUtils
 * @Author: liuyu
 * @Date: Created in 2020/10/27 8:40
 * @Version: 1
 * @Modified By:
 */
public class GlobalExecutorUtils {
    private static final int CORE = Runtime.getRuntime().availableProcessors();
    public static final ThreadFactory THREAD_FACTORY = new ThreadFactoryBuilder()
            .setNameFormat("global-task-pool-%d").build();
    private static final ExecutorService EXECUTOR_SERVICE = new ThreadPoolExecutor(CORE * 2, CORE * 4, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10000), THREAD_FACTORY);
    private static final ScheduledExecutorService SCHEDULED_EXECUTOR_SERVICE = new ScheduledThreadPoolExecutor(CORE * 4, new BasicThreadFactory.Builder().namingPattern("global-task-schedule-pool-%d").daemon(true).build());


    /**
     * 异常不会抛出，需要通过future.get()
     *
     * @param task
     * @return void
     * @author liuyu
     * @date 2021/3/12 11:25
     */
    public static Future summit(Runnable task) {
        return EXECUTOR_SERVICE.submit(task);
    }

    /**
     * 异常直接排除
     *
     * @param task
     * @return void
     * @author liuyu
     * @date 2021/3/12 11:37
     */
    public static void execute(Runnable task) {
        EXECUTOR_SERVICE.execute(task);
    }


    /**
     * 周期性执行任务，执行任务的周期固定
     *
     * @param runnable     任务
     * @param initialDelay 首次延迟时间
     * @param period       周期
     * @param timeUnit     时间单位
     * @return java.util.concurrent.ScheduledFuture
     * @throws
     * @author USER
     * @date 2023/2/22 16:42
     */
    public static ScheduledFuture scheduleAtFixedRate(Runnable runnable, long initialDelay, long period, TimeUnit timeUnit) {
        return SCHEDULED_EXECUTOR_SERVICE.scheduleAtFixedRate(runnable, initialDelay, period, timeUnit);
    }

    /**
     * 周期性执行任务 ,执行完毕后与下一次的
     *
     * @param runnable
     * @param initialDelay
     * @param delay
     * @param timeUnit
     * @return java.util.concurrent.ScheduledFuture
     * @throws
     * @author USER
     * @date 2023/2/22 16:44
     */
    public static ScheduledFuture scheduleWithFixedDelay(Runnable runnable, long initialDelay, long delay, TimeUnit timeUnit) {
        return SCHEDULED_EXECUTOR_SERVICE.scheduleWithFixedDelay(runnable, initialDelay, delay, timeUnit);
    }

    /**
     * 延迟执行
     *
     * @param runnable 任务
     * @param delay    延迟时间
     * @param timeUnit 延迟单位
     * @return java.util.concurrent.ScheduledFuture
     * @throws
     * @author USER
     * @date 2023/2/22 16:41
     */

    public static ScheduledFuture schedule(Runnable runnable, long delay, TimeUnit timeUnit) {
        return SCHEDULED_EXECUTOR_SERVICE.schedule(runnable, delay, timeUnit);
    }
}
